package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Service
public class UploadService {

    private static final Logger logger= LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;//fastDfs访问的客户端对象

    public String uploadImage(MultipartFile file){
        try {
            Set<String> ext = new HashSet<>();
            ext.add("image/jpeg");
            ext.add("image/png");

            String contentType = file.getContentType();
            System.out.println(contentType);

            //1.校验文件类型
            if (!ext.contains(contentType)) {
                logger.info("文件类型不匹配,{},请校验", contentType);
            }

            //2.校验文件的内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null){
                logger.info("文件内容不匹配请校验");
            }

            //实现文件上传逻辑
            String originalFilename = file.getOriginalFilename();

            //从字符串中最后一个.开始截取
            String ext1 = StringUtils.substringAfterLast(originalFilename, ".");

            //输入流,文件大小,后缀
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext1, null);

            //返回文件上传后的地址
            return "http://image.leyou.com/"+storePath.getFullPath();

        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
}
